package com.hedl.practice.diyJava.gather.study_queue.test;

import java.util.LinkedList;
import java.util.Queue;

/**
 *
                            throw Exception	        返回false或null
        添加元素到队尾	    add(E e)	            boolean offer(E e)
        取队首元素并删除	    E remove()	            E poll()
        取队首元素但不删除	    E element()	            E peek()
 */
public class StudyQueue {
    public static void main(String[] args) {
        /**
         * 注意：不要把null添加到队列中，否则poll()方法返回null时，很难确定是取到了null元素还是队列为空。
         */
        Queue<String> q = new LinkedList<>();
        Queue<String> queue = new LinkedList<>();

        //两种添加方式
        //添加失败会抛出异常
        try{
            q.add("Apple");
            System.out.println("添加成功");
        }catch (IllegalStateException e){
            System.out.println("添加失败");
        }

        //如果添加失败会返回false
        /*if (q.offer("Apple")){
            System.out.println("添加成功");
        }else {
            System.out.println("添加失败");
        }*/


        //从Queue中取出队首元素，获取失败会抛出异常
        /*try{
            q.remove();
            System.out.println("获取成功");
        }catch (IllegalStateException e){
            System.out.println("获取失败");
        }*/
        //如果调用poll()方法取出队首元素，失败会返回null
        String poll = q.poll();
        if (poll != null){
            System.out.println("获取成功");
        }else {
            System.out.println("获取失败");
        }


        //添加三个元素
        queue.offer("apple");
        queue.offer("pear");
        queue.offer("banana");
        //获取队首元素并删除
        System.out.println(queue.poll());       //apple
        System.out.println(queue.poll());       //pear
        System.out.println(queue.poll());       //banana
        System.out.println(queue.poll());       //null


        //因为上面执行了删除这里在添加一边
        queue.offer("apple");
        queue.offer("pear");
        queue.offer("banana");
        //获取队首元素，不删除
        System.out.println(queue.peek());       //apple
        System.out.println(queue.peek());       //apple
        System.out.println(queue.peek());       //apple
        System.out.println(queue.peek());       //apple

    }
}
